package com.cnunicom.common.utils;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: dingziyuan
 * @Date: 2019/12/12 9:41
 * @Description: 二维码工具类
 */
@Data
@Component
public class QRCodeUtils {

    @Resource
    private FastdfsClientUtil fastdfsClientUtil;


    public QRCodeUtils() {
    }


    /**
     * 二维码上传处理
     *
     * @param content 二维码内容
     * @return 二维码图片访问全路径
     */
    public String packageUrlForLink(String content, String logoURL, String text) {
        String fullPath = "";
        BufferedImage image = getBufferedImage(content, logoURL, text);
        try {
            //以流的形式将图片上传到fastdfs上
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            fullPath = fastdfsClientUtil.uploadQRCode(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fullPath;
    }


    /**
     * 获取BufferedImage对象
     *
     * @param content
     * @param logoURL
     * @return
     */
    public BufferedImage getBufferedImage(String content, String logoURL, String text) {

        try {
            final BufferedImage image = QrCodeGenWrapper.of(content)
                    .setW(500)
                    .setH(500)
                    //                    .setDetectImg("detect.png")
                    .setDrawPreColor(0xff008e59)
                    //                    .setDrawPreColor(0xff002fa7)
                    .setErrorCorrection(ErrorCorrectionLevel.M)
                    .setLogoStyle(QrCodeOptions.LogoStyle.ROUND)
                    .setLogoBgColor(Color.LIGHT_GRAY)
                    .setLogo(logoURL)
                    .setPadding(0)
                    .setLogoRate(10)
                    .setDrawStyle(QrCodeOptions.DrawStyle.CIRCLE)
                    .setDrawEnableScale(true)
                    .asBufferedImage();

            return insertWords(image, text);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 把带logo的二维码下面加上文字
     * @param image
     * @param words
     * @return
     */
    private static BufferedImage insertWords(BufferedImage image,String words){

        int WIDTH = 500;
        int HEIGHT = 540;

        // 新的图片，把带logo的二维码下面加上文字
        if (StringUtils.isNotEmpty(words)) {

            //创建一个带透明色的BufferedImage对象
            BufferedImage outImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
            Graphics2D outg = outImage.createGraphics();
            setGraphics2D(outg);

            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color=new Color(183,183,183);
            outg.setColor(color);
            // 字体、字型、字号
            outg.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            //文字长度
            int strWidth = outg.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  （居中显示）
            int wordStartX=(WIDTH - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY=HEIGHT - 10;
            // 画文字
            outg.drawString(words, wordStartX, wordStartY);
            outg.dispose();
            outImage.flush();
            return outImage;

                /*if (strWidth > 399) {
                    // 长度过长就截取前面部分 然后换行
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(1000, 1120, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
               // 字体、字型、字号
                    outg2.setFont(new Font("宋体", Font.BOLD, 30));
               // 画文字
                    outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } */
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  （抗锯齿）
     * @param graphics2D
     */
    private static void setGraphics2D(Graphics2D graphics2D){
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        graphics2D.setStroke(s);
    }


}
